package com.ruyuan.seckilling.aggr.controller;

import com.ruyuan.dependency.product.api.ProductApi;
import com.ruyuan.dependency.product.vo.SkuVo;
import com.ruyuan.seckilling.common.FileNameUtils;
import com.ruyuan.seckilling.common.FilePathUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author zhonghuashishan
 */
@RestController
public class SeckillingActivityAggrController {

    @Autowired
    private ProductApi productApi;

    // 参数示例
    // .params(ImmutableMap.of("activityId", id,
    // "activityName", activity.getActivityName(),
    // "startTime", activity.getStartTime(),
    // "endTime", activity.getEndTime(),
    // "skuIds", skuIds))
    @PostMapping("/seckilling/activity")
    public Map aggr(@RequestBody Map params) {
        Map aggrData = new LinkedHashMap();
        aggrData.put("activityId", params.get("activityId"));
        aggrData.put("startTime", params.get("startTime"));
        aggrData.put("endTime", params.get("endTime"));
        List<Integer> rawList = (List<Integer>) params.get("skuIds");
        List<Long> skuIds = rawList.stream().map(e -> Long.parseLong(String.valueOf(e))).collect(Collectors.toList());
        List<SkuVo> skuVos = productApi.queryBySkuIds(skuIds);
        for (int i = 0; i < skuVos.size(); i++) {
            SkuVo skuVo = skuVos.get(i);
            String seckillingProductFilename = FileNameUtils.generateSeckillingProductFilename(skuVo.getId());
            String productUrl = FilePathUtils.generateVisitUrl(seckillingProductFilename);
            aggrData.put("skuId" + (i + 1), skuVo.getId());
            aggrData.put("image" + (i + 1), skuVo.getImage());
            aggrData.put("url" + (i + 1), productUrl);
        }
        return aggrData;
    }
}
